#include "util.h"
#include "client.h"
#include <sys/epoll.h>
#include<sys/socket.h>
#include <unistd.h>
#include<stdlib.h>
#include<string.h>
#define MAX_EVENTS 10
#define BUFFER_SIZE 1000

int main()
{
	// 建立TCP连接
	int clientFd = tcpConnection("127.0.0.1", "12345");
	errif(clientFd == -1,"client connection failed");
    if(setNonBlocking(clientFd)==-1)
    {
        printf("Failed to set non-blocking mode\n");
		close(clientFd);
		return -1;
    }

	char buf[BUFFER_SIZE];
	train_t cmdStr;

	
	int epfd = epoll_create1(0);
	errif(epfd == -1, "epoll_create1 error");

	epollAdd(epfd,STDIN_FILENO);
    epollAdd(epfd,clientFd);
	struct epoll_event events[MAX_EVENTS];

	while (1) {
		int numEvents = epoll_wait(epfd, events, MAX_EVENTS, -1);
		errif(numEvents == -1, "epoll_wait error");

		for (int i = 0; i < numEvents; ++i) {
			int fd = events[i].data.fd;
			// 处理标准输入事件,准备发送命令
			if (fd == STDIN_FILENO) {
			    memset(buf,0,sizeof(buf));
                int ret = read(STDIN_FILENO,buf,sizeof(buf));
                errif(ret == -1,"read cmd error");
                if(ret == 0)
                {
                    printf("EXIT\n");
                    break;
                }
                memset(&cmdStr,0,sizeof(cmdStr));
                buf[strlen(buf)-1]='\0';
                parseCommand(buf,strlen(buf),&cmdStr);
                printf("cmdStr.taskType:%d\n",cmdStr.taskType);
                printf("cmdStr._length:%d\n",cmdStr._length);
                printf("cmdStr._data:%s\n",cmdStr._data);
                //此时命令已经解析完成，放到了train协议里面


                if(cmdStr.taskType ==CMD_TYPE_PUTS){
                    //发送train协议，此时puts 后面已经跟着了文件名
                    //在上传过程中，省略掉有关于文件名的发送，直接发送大小和内容
                    

                }
                else if(cmdStr.taskType == CMD_TYPE_GETS){

                }else{
                    sendn(clientFd,&cmdStr,4+4+cmdStr._length);
                }
			}
			// 处理服务器返回的消息
			else if (fd == clientFd) {
				memset(buf, 0, sizeof(buf));
				int ret = recv(clientFd, buf, sizeof(buf), 0);
				// 服务器关闭连接
				if (ret == 0) {
					printf("Server closed the connection\n");
					close(clientFd);
					epoll_ctl(epfd, EPOLL_CTL_DEL, clientFd,
						  NULL); // 从epoll中移除
					return 0;
				} else if (ret == -1) {
					perror("recv error");
					close(clientFd);
					return -1;
				}
				// 打印服务器返回的消息
				printf("%s\n", buf);
			}
		}
	}
	close(clientFd);
	return 0;
}
